<template>
  <div class="option-wrapper">
    <div class="option-main">
      <a-form layout="vertical" :model="formState" :rules="rules">
        <div class="option-column">
          <div class="column-title">报修信息</div>
          <a-descriptions bordered :labelStyle="{ width: '120px' }" :contentStyle="{ width: '500px' }"
            :column="{ xxl: 1, xl: 1, lg: 1, md: 1, sm: 1, xs: 1 }">
            <a-descriptions-item label="出故障日期">{{ repairInfo.breakdown_date || '暂无' }}</a-descriptions-item>
            <a-descriptions-item label="附件">
              <template v-if="repairInfo.files && repairInfo.files.length > 0">
                <div v-for="(file, index) in repairInfo.files" :key="file.fileId || index" style="margin-bottom: 8px;">
                  <a-image v-if="file.url && isImageFile(file.file_content_type)" :style="{ display: 'none' }" :preview="{
                    visible: visibleImages[index],
                    onVisibleChange: (value) => setImageVisible(index, value),
                  }" :width="0" :src="file.url" />
                  <a-button type="link" size="small" @click="() => handleFileClick(file, index)">
                    {{ file.file_name || '附件' + (index + 1) }}
                  </a-button>
                  <span style="margin-left: 8px; color: #999; font-size: 12px;">
                    ({{ formatFileSize(file.file_size) }})
                  </span>
                </div>
              </template>
              <span v-else>暂无附件</span>
            </a-descriptions-item>
            <a-descriptions-item label="故障描述" span="2">{{ repairInfo.description || '暂无描述' }}</a-descriptions-item>
          </a-descriptions>
        </div>
        <div class="option-column">
          <div class="column-title">处理报修</div>
          <div class="column-content">
            <div class="content-item">
              <a-form-item label="分配维修人" name="name">
                <a-select v-model:value="formState.name" placeholder="请选择维修人" :options="userOptions"
                  :loading="userOptionsLoading" show-search :filter-option="false" @search="handleUserSearch" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="记录内容" name="content">
                <a-textarea v-model:value="formState.content" placeholder="请输入维修人姓名" />
              </a-form-item>
            </div>
            <div class="content-item">
              <a-form-item label="是否关单" name="content">
                <a-switch v-model:checked="formState.checked" />
              </a-form-item>
            </div>
          </div>
        </div>
        <div class="option-column">
          <div class="column-title">处理流程</div>
          <a-table class="table-inner" :row-selection="rowSelection" :columns="columns" :scroll="{ x: 700 }"
            :dataSource="tableData" :loading="tableLoading" :pagination="false" @change="onChange">
          </a-table>
        </div>
        <div class="option-footer">
          <a-button class="opt-btn"  @click="handleBack">取消</a-button>
          <a-button class="opt-btn" type="primary" @click="handleSave">保存</a-button>
        </div>
      </a-form>
    </div>
  </div>
</template>
<script setup>
import { ref, computed, onMounted } from "vue";
import { useRoute,useRouter } from "vue-router";
import { PlusOutlined } from "@ant-design/icons-vue";
import { message } from "ant-design-vue";
import api from "@/api";

const route = useRoute();
const router = useRouter();
const handleBack = () => {
  router.back();
};
const formState = ref({
  name: "",
  content: "",
  checked:false
});

// 用户选项相关
const userOptions = ref([]);
const userOptionsLoading = ref(false);

// 处理流程相关
const tableData = ref([]);
const tableLoading = ref(false);

// 报修信息相关
const repairInfo = ref({
  breakdown_date: '',
  files: [],
  description: ''
});

// 图片预览相关
const visible = ref(false);
const visibleImages = ref({});
const setVisible = (value) => {
  visible.value = value;
};
const setImageVisible = (index, value) => {
  visibleImages.value[index] = value;
};

// 判断是否为图片文件
const isImageFile = (contentType) => {
  if (!contentType) return false;
  return contentType.startsWith('image/');
};

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (!bytes) return '未知大小';
  const sizes = ['B', 'KB', 'MB', 'GB'];
  const i = Math.floor(Math.log(bytes) / Math.log(1024));
  return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
};

// 处理文件点击
const handleFileClick = (file, index) => {
  if (file.url && isImageFile(file.file_content_type)) {
    // 如果是图片，显示预览
    setImageVisible(index, true);
  } else if (file.url) {
    // 如果是其他文件，直接下载
    window.open(file.url, '_blank');
  }
};

// 获取用户选项
const getUserOptions = async (searchText = '') => {
  try {
    userOptionsLoading.value = true;
    const response = await api.apiUserOptionsPost({
      searchText: searchText,
      pageSize: 50
    });
    if (response.data) {
      userOptions.value = response.data.map(item => ({
        label: item.text,
        value: item.value
      }));
    }
  } catch (error) {
    console.error('获取用户选项失败:', error);
  } finally {
    userOptionsLoading.value = false;
  }
};

// 搜索用户
const handleUserSearch = (searchText) => {
  getUserOptions(searchText);
};

// 获取报修信息详情
const getRepairInfo = async (repairId) => {
  try {
    const response = await api.apiRepairFetchModelPost({
      repair_id: repairId
    });
    console.log('报修信息详情:', response.data);

    if (response.data) {
      repairInfo.value = {
        breakdown_date: response.data.breakdown_date || '',
        files: response.data.files || [],
        description: response.data.description || '',
      };
    }
  } catch (error) {
    console.error('获取报修信息失败:', error);
  }
};

// 获取处理流程历史
const getRepairHistory = async (repairId) => {
  try {
    tableLoading.value = true;
    const response = await api.apiRepairHistoryPagedListPost({
      pageIndex: 1,
      pageSize: 100,
      args: {
        repair_id: repairId
      }
    });
    console.log('处理流程历史:', response.data.data);

    if (response.data.data) {
      tableData.value = response.data.data.map(item => ({
        name: item.user_real_name || '未分配',
        content: item.remark || '',
        time: item.updated || ''
      }));
    }
  } catch (error) {
    console.error('获取处理流程失败:', error);
  } finally {
    tableLoading.value = false;
  }
};
const columns = ref([
  {
    dataIndex: "name",
    title: "维修人",
    width: 100,
  },
  {
    dataIndex: "content",
    title: "处理内容",
    ellipsis: true,
  },
  {
    dataIndex: "time",
    title: "时间",
    width: 200,
  },
]);

const rules = ref({
  name: [
    {
      required: true,
      message: "请输入客户名称",
      trigger: "blur",
    },
  ],
  no: [
    {
      required: true,
    },
  ],
  class: [
    {
      required: true,
      message: "请选择客户分类",
      trigger: "change",
    },
  ],
});
const resetForm = () => {
  formState.value = {
    name: "",
    content: "",
    checked:false
  };
};

// 保存处理记录
const handleSave = async () => {
  try {
    const repairId = route.query.id;
    if (!repairId) {
      console.error('缺少repair_id参数');
      return;
    }

    if (!formState.value.name || !formState.value.content) {
      console.error('请填写完整的维修人和记录内容');
      return;
    }

    const response = await api.apiRepairHistoryCreatePost({
      repair_id: repairId,
      user_id: formState.value.name, // 维修人的user_id
      remark: formState.value.content // 记录内容
    });

    console.log('保存成功:', response.data);

    if(formState.value.checked){
         const response = await api.apiRepairFetchModelPost({
          repair_id: repairId
        });
        console.log('报修信息详情:', response.data);
        let obj = ref(response.data)
        obj.value.closed = true;
        await api.apiRepairUpdatePost(obj.value)
    }
    message.success('处理记录保存成功！');

    // 保存成功后重新加载处理流程数据
    await getRepairHistory(repairId);

    // 清空表单
    resetForm();
  } catch (error) {
    console.error('保存失败:', error);
    message.error('保存失败，请重试！');
  }
};

// 组件挂载时获取用户选项、报修信息和处理流程
onMounted(() => {
  getUserOptions();
  // 从路由参数获取repair_id
  const repairId = route.query.id;
  if (repairId) {
    getRepairInfo(repairId);
    getRepairHistory(repairId);
  }
});
</script>
